package cn.calm.user.interceptor;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.osgi.BundleAccessor;
import org.apache.struts2.osgi.DefaultBundleAccessor;

import cn.calm.user.action.UserAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SessionInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger
			.getLogger(SessionInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session = request.getSession();

		Object user = session.getAttribute(UserAction.SESSION_KEY_USER);
		ActionSupport action = (ActionSupport) invocation.getAction();
		if (user == null) {
			LOGGER.debug("SESSION_KEY_USER is null");
			action.addActionError("EMUM0005");
			if(isAjaxRequest(request)){
				return "ajaxLogin";
			}
			ServletContext ctx=	ServletActionContext.getServletContext();
			Dispatcher dispatcher=(Dispatcher) ctx.getAttribute(StrutsStatics.SERVLET_DISPATCHER);
			Configuration config= dispatcher.getConfigurationManager().getConfiguration();
			for(String configName:config.getPackageConfigNames()){
				PackageConfig packageConf=config.getPackageConfig(configName);
				Map<String,ResultConfig> globle=packageConf.getGlobalResultConfigs();
				ResultConfig result=globle.get("login");
				if(result!=null){
					String symbolicName=DefaultBundleAccessor.getInstance().getSymbolicNameByPackageName(packageConf.getName());
					if(symbolicName!=null){
						session.setAttribute(BundleAccessor.CURRENT_BUNDLE_NAME, symbolicName);
					}
					break;
				}
			}
			return "login";
		}
		return invocation.invoke();
	}
	
	/**
	 * 判断是否为Ajax请求
	 * @param request   HttpServletRequest
	 * @return  是true, 否false
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
	    String requestType = request.getHeader("X-Requested-With");
	    if (requestType != null && requestType.equals("XMLHttpRequest")) {
	        return true;
	    } else {
	        return false;
	    }
	}
}
